﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Limiting
{
    public class MemoryCatchLimiting : ILimiting
    {
        private readonly IMemoryCache _db;
        private readonly LimitingOptions _options;

        public MemoryCatchLimiting(IMemoryCache db,
           LimitingOptions options)
        {
            _db = db;
            _options = options;
        }

        public Task<bool> CheckIdentityLimited(string identity)
        {
            if (_options.Allows.Contains(identity))
                return Task.FromResult(false);
            //把这个key的访问记录拿出来
            _db.TryGetValue(identity, out List<DateTime> items);
            //防止null引用
            items ??= new();
            //这次访问的时间加进去
            items.Add(DateTime.Now);
            //算出时间范围
            var timeout = DateTime.Now.AddSeconds(-_options.Time.TotalSeconds);
            //删除不在时间范围的item
            items.RemoveAll(x => x < timeout);
            //达到限流返回true
            if (items.Count > _options.Limit)
                return Task.FromResult(true);
            //结果重新缓存
            _db.Set(identity, items);
            return Task.FromResult(false);
        }
    }
}
